<?php


namespace app\cms\admin\controller\addons;


use app\cms\community\lib\utils\addons\downloadAddons;
use app\cms\community\lib\utils\addons\uploadAddons;
use app\cms\model\addons\addonsModel;
use iflow\auth\Authorize\AuthAnnotation;
use iflow\Container\implement\annotation\tools\data\Inject;
use iflow\Response;
use iflow\Router\Controller;
use app\cms\community\lib\utils\addons\exception\{addonsEmptyException, addonsException};
use iflow\Router\implement\Request\DeleteMapping;
use iflow\Router\implement\Request\GetMapping;
use iflow\Router\implement\Request\PostMapping;

#[Controller('%cmsAdmin%/addons')]
class addonsController {

    #[Inject]
    public addonsModel $addonsModel;


    /**
     * 新增插件
     * @param int $type
     * @return Response
     * @throws addonsEmptyException
     * @throws addonsException
     */
    #[PostMapping]
    #[AuthAnnotation('user', 'addonsReadWrite|addonsWrite')]
    public function addAddons(
        int $type
    ): Response {
        $downloadUrl = request() -> params('download');
        if ($downloadUrl) {
            $save = (new downloadAddons($type)) -> gitCloneAddons($downloadUrl);
        } else {
            $file = request() -> file('file');
            if (!$file) return message() -> parameter_error('请选择需要上传的插件');
            $save = (new uploadAddons($type)) -> setUploadFile(is_array($file) ? $file[0] : $file);
        }
        if ($save -> save()) {
            return message() -> success('保存插件成功');
        }
        return message() -> success('保存插件失败');
    }

    /**
     * 获取插件列表
     * @param string $addons_name
     * @return Response
     */
    #[GetMapping]
    #[AuthAnnotation('user', 'addonsReadWrite|addonsRead')]
    public function getAddonsList(string $addons_name): Response
    {
        // TODO: 获取已安装的插件列表
        return $this->addonsModel -> getAddonsList($addons_name);
    }

    /**
     * 删除插件
     * @param string $addons_ns_code
     * @return Response
     */
    #[DeleteMapping('remove_addons/<[\S\W\w\s]+:addons_ns_code>')]
    #[AuthAnnotation('user', 'addonsReadWrite|addonsWrite')]
    public function removeAddons(string $addons_ns_code): Response
    {
        // TODO: 删除插件
        return $this->addonsModel -> deleteAddons($addons_ns_code);
    }

}